﻿using System;
using System.IO;
using System.Net;
using Common.Enums;

namespace Infrastructure.Web
{
    public class WebRequest : IWebRequest
    {
        public string PerformJsonWebRequest(WebMethod method, string url, string postData)
        {
            var webRequest = BuildWebRequest(url, method, postData);
            return GetJsonWebResponse(webRequest);
        }

        public Stream PerformStreamWebRequest(WebMethod method, string url, string postData)
        {
            var webRequest = BuildWebRequest(url, method, postData);
            return GetStreamWebResponse(webRequest);
        }

        private HttpWebRequest BuildWebRequest(string url, WebMethod method, string postData)
        {
            StreamWriter requestWriter;

            var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            if (webRequest == null)
                return null;

            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;
            //webRequest.UserAgent  = "[You user agent]";
            webRequest.Timeout = 20000;
            if (method == WebMethod.Post)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";
                //POST the data.
                using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(postData);
                }
            }
            return webRequest;
        }

        private string GetJsonWebResponse(HttpWebRequest webRequest)
        {
            StreamReader responseReader = null;
            string responseData;

            using(var responseStream = webRequest.GetResponse().GetResponseStream())
            {
                if (responseStream == null)
                    return string.Empty;

                using (responseReader = new StreamReader(responseStream))
                {
                    responseData = responseReader.ReadToEnd();
                }
            }
            return responseData;
        }

        private Stream GetStreamWebResponse(HttpWebRequest webRequest)
        {
            return webRequest.GetResponse().GetResponseStream();
        }
    }
}
